package com.jiangjun.fetch.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.util.Base64;
import com.jiangjun.fetch.util.ResponseSender;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@WebServlet(name = "GetContentServlet", urlPatterns = "/getContentService", asyncSupported = false)
@WebInitParam(name = "default_charset", value = "utf-8")
public class GetContentServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String txt_path = request.getParameter("src");
		txt_path = new String(Base64.decode(txt_path));
		InputStream is = null;
		InputStreamReader reader = null;
		BufferedReader buf = null;
		StringBuffer sb = new StringBuffer();
		try {
			File file = null;
			file = new File(txt_path);
			is = new FileInputStream(file);
			reader = new InputStreamReader(is);
			buf = new BufferedReader(reader);
			String line = null;
			while ((line = buf.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != buf)
				buf.close();
			if (null != reader)
				reader.close();
			if (null != is)
				is.close();
		}
		String content = sb.toString();
		String accept = request.getHeader("Accept-Encoding");
		if (accept != null && accept.toLowerCase().contains("gzip")) {
			ResponseSender.sendGzipResponse(response,
					content.getBytes("utf-8"), "utf-8", null);
		} else {
			ResponseSender.sendResponse(response, content.getBytes("utf-8"),
					"utf-8", null);
		}
	}
}
